package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.model.common.constants.admin.AdminConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmUserDTO;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.model.wemedia.vos.WmUserVO;
import com.heima.utils.common.AppJwtUtil;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmUserService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {



    @Override
    public ResponseResult login(WmUserDTO dto) {
        //校验参数
        if (StringUtils.isBlank(dto.getName())||StringUtils.isBlank(dto.getPassword())) {
            CustException.cust(AppHttpCodeEnum.PARAM_REQUIRE,"缺少信息");
        }
        //查询自媒体用户,根据用户名查
        WmUser wmUser = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        //查看是否存在用户
        if (wmUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"用户不存在");
        }
        //校验状态
        if (!AdminConstants.USER_STATUS_ALLOW.equals(wmUser.getStatus())) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"该用户状态异常，请联系管理员");
        }
        //校验密码
        String inputPwd = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());
        if (!inputPwd.equals(wmUser.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token并封装
        String token = AppJwtUtil.getToken(Long.valueOf(wmUser.getId()));
        HashMap<String, Object> map = new HashMap<>();
        map.put("token",token);
        WmUserVO wmUserVO = new WmUserVO();
        try {
            BeanUtils.copyProperties(wmUser,wmUserVO);
        } catch (Exception e) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,e.getMessage());
        }
        map.put("user",wmUserVO);
        return ResponseResult.okResult(map);
    }
}
